"""
FileName：notifier.py
Description：
Author：gaojiahui
Time：2025/8/26 11:56
Website：https://gitee.com/gao-jiahui
"""
from typing import List, Dict, Any

import requests

from config.settings import settings
from core.logger import logger


class Notifier:
    """通知工具类"""

    def __init__(self):
        self.dingtalk_webhook = settings.DINGTALK_WEBHOOK
        self.dingtalk_secret = settings.DINGTALK_SECRET
        self.enabled = settings.NOTIFICATION_ENABLED

    def send_dingtalk_message(self, title: str, text: str, at_mobiles: List[str] = None, is_at_all: bool = False):
        """发送钉钉消息"""
        if not self.enabled or not self.dingtalk_webhook:
            logger.warning("钉钉通知未启用或未配置webhook")
            return False

        try:
            # 构建消息内容
            message = {
                "msgtype": "markdown",
                "markdown": {
                    "title": title,
                    "text": text
                },
                "at": {
                    "atMobiles": at_mobiles or [],
                    "isAtAll": is_at_all
                }
            }

            # 如果有secret，需要签名
            if self.dingtalk_secret:
                import time
                import hmac
                import hashlib
                import base64
                import urllib.parse

                timestamp = str(round(time.time() * 1000))
                secret_enc = self.dingtalk_secret.encode('utf-8')
                string_to_sign = '{}\n{}'.format(timestamp, self.dingtalk_secret)
                string_to_sign_enc = string_to_sign.encode('utf-8')
                hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
                sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

                webhook = f"{self.dingtalk_webhook}&timestamp={timestamp}&sign={sign}"
            else:
                webhook = self.dingtalk_webhook

            # 发送请求
            response = requests.post(webhook, json=message, timeout=10)
            result = response.json()

            if result.get("errcode") == 0:
                logger.info("钉钉消息发送成功")
                return True
            else:
                logger.error(f"钉钉消息发送失败: {result.get('errmsg')}")
                return False
        except Exception as e:
            logger.error(f"发送钉钉消息异常: {str(e)}")
            return False

    # def send_wechat_message(self, title: str, text: str):
    #     """发送企业微信消息"""
    #     if not self.enabled or not self.wechat_webhook:
    #         logger.warning("企业微信通知未启用或未配置webhook")
    #         return False
    #
    #     try:
    #         # 构建消息内容
    #         message = {
    #             "msgtype": "markdown",
    #             "markdown": {
    #                 "content": f"## {title}\n{text}"
    #             }
    #         }
    #
    #         # 发送请求
    #         response = requests.post(self.wechat_webhook, json=message, timeout=10)
    #         result = response.json()
    #
    #         if result.get("errcode") == 0:
    #             logger.info("企业微信消息发送成功")
    #             return True
    #         else:
    #             logger.error(f"企业微信消息发送失败: {result.get('errmsg')}")
    #             return False
    #
    #     except Exception as e:
    #         logger.error(f"发送企业微信消息异常: {str(e)}")
    #         return False

    def send_test_report(self, test_results: Dict[str, Any]):
        """发送测试报告"""
        if not self.enabled:
            return False

        # 准备报告内容
        total = test_results.get("total", 0)
        passed = test_results.get("passed", 0)
        failed = test_results.get("failed", 0)
        skipped = test_results.get("skipped", 0)
        duration = test_results.get("duration", 0)

        success_rate = (passed / total * 100) if total > 0 else 0

        # 构建消息标题
        title = "✅ 测试通过" if failed == 0 else "❌ 测试失败"
        title += f" - 通过率: {success_rate:.2f}%"

        # 构建消息内容
        text = f"""
### 测试执行结果
- **总计**: {total} 个测试用例
- **通过**: {passed} 个
- **失败**: {failed} 个  
- **跳过**: {skipped} 个
- **持续时间**: {duration:.2f} 秒
- **通过率**: {success_rate:.2f}%

### 详细信息
"""

        # 添加失败用例详情
        if failed > 0 and "failed_cases" in test_results:
            text += "\n**失败用例:**\n"
            for case in test_results["failed_cases"][:5]:   # 最多显示5个失败用例
                text += f"- {case.get('name','未知用例')}: {case.get('reason', '未知原因')}\n"

            if failed > 5:
                text += f"- ... 还有 {failed - 5} 个失败用例\n"

        # 发送到钉钉和企业微信
        dingtalk_success = self.send_dingtalk_message(title, text)
        # wechat_success = self.send_wechat_message(title, text)

        return dingtalk_success # or wechat_success

# 全局通知器实例
notifier = Notifier()
